<template>
  <div>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="layui-row">
        <div
          v-if="isSysGroup"
          style="padding-right: 20px"
          class="layui-col-md6 select-depot-storage"
        >
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="leftFilterInfo.query.queryMap"
            :query-more-json="true"
            :filter-list="leftFilterInfo.searchList"
            :filter-btn="leftFilterInfo.searchBtn"
          >
          </NewPageFilter>
          <dialog-table
            ref="productTable"
            :refresh="leftTableInfo.refresh"
            :init-curpage="leftTableInfo.initCurpage"
            v-model:data="leftTableInfo.data"
            :api="leftTableInfo.api"
            class="productTable"
            :reserve-selection="true"
            :listen-height="false"
            :selectable="selectable"
            :query="leftFilterInfo.query"
            :field-list="leftTableInfo.fieldList"
            :highlight-row="isSysGroup ? highlightRow : false"
            :check-box="checkBox"
            :is-row-click-select="!isSysGroup"
            @handleEvent="leftHandleEvent"
          >
          </dialog-table>
        </div>
        <div
          class="select-depot-storage"
          :class="isSysGroup ? 'layui-col-md6' : 'layui-col-md12'"
        >
          <NewPageFilter
            v-model:query="rightFilterInfo.query.queryMap"
            :query-more-json="true"
            :filter-list="rightFilterInfo.searchList"
            :filter-btn="rightFilterInfo.searchBtn"
          >
          </NewPageFilter>
          <el-form ref="tableForm" :model="rightTableInfo" style="width: 100%">
            <dialog-table
              ref="batchNumberTable"
              :refresh="rightTableInfo.refresh"
              :init-curpage="rightTableInfo.initCurpage"
              v-model:data="rightTableInfo.data"
              :api="rightTableInfo.api"
              :reserve-selection="true"
              :listen-height="false"
              :query="rightFilterInfo.query"
              :field-list="rightTableInfo.fieldList"
              :check-box="checkBox"
              @handleEvent="rightHandleEvent"
            >
              <template v-slot:col-editQty="scope">
                <el-form-item
                  v-if="
                    scope.row.codeType === 1 ||
                    scope.row.codeType === 4 ||
                    (scope.row.codeType === 2 && !scope.row.uniqueCode) ||
                    (scope.row.codeType === 3 && !scope.row.factoryMainCode) ||
                    (scope.row.codeType === 3 && !scope.row.factorySubCode)
                  "
                  class="margin-bottom"
                  @click.stop=""
                >
                  <div class="page-table-input-number-wrapper">
                    <div class="page-table-input-number-left">
                      <div class="page-table-input-number-item">
                        <el-form-item>
                          <el-input-number
                            v-model.lazy="scope.row.largeUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="
                              scope.row.qtyOperateMode === 0 ||
                              scope.row.qtyOperateMode === 2
                                ? 0
                                : systemConfig.qty_show_precision
                            "
                            :min="0"
                            :max="largeMax(scope.row)"
                            @change="changeLarge($event, scope.row)"
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.unitName }}
                        </div>
                      </div>
                      <div
                        v-if="
                          scope.row.unitConvertCoefficient > 1 &&
                          scope.row.qtyOperateMode === 2
                        "
                        class="page-table-input-number-item"
                      >
                        <el-form-item>
                          <el-input-number
                            v-model.lazy="scope.row.smallUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="0"
                            :min="0"
                            :max="smallMax(scope.row)"
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.calcUnitName }}
                        </div>
                      </div>
                    </div>
                    <div
                      v-if="scope.row.qtyOperateMode === 2"
                      class="page-table-input-number-right"
                    >
                      {{ $fn.qtyFormatter(scope.row.editQty) }}
                    </div>
                  </div>
                </el-form-item>
                <span
                  v-else-if="
                    scope.row.codeType === 2 || scope.row.codeType === 3
                  "
                  >{{ $fn.qtyFormatter(scope.row.editQty) }}</span
                >
              </template>
            </dialog-table>
          </el-form>
        </div>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="selectDepotStorage">
import PageDialog from '@/components/PageDialog/index'
import DialogTable from '@/components/DialogTable/index'

import { getDepotStockCustomizeListPage } from '@/api/stock.js'
import { getCustomizeSetting } from '@/api/customize'
import * as _ from 'lodash'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: true,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getDepotStockCustomizeListPage,
  },
  excludeQueryList: {
    type: Array,
    default: function () {
      return []
    },
  },
  showPrice: {
    type: Boolean,
  },
  showDialog: {
    type: Boolean,
  },
  leftTableKey: {
    type: String,
    default:
      'productPageWithDepotStockLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  },
  rightTableKey: {
    type: String,
    default:
      'productPageWithDepotStockRight-com.slip.spd.entity.vo.stock.DepotStockVO',
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
})

// 过滤相关配置
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const isSysGroup = ref(false)
const selectRow = ref([])
const clickRow = ref({})
const searchObj = ref('')
const groupArr = ref('')
const clickRowMap = ref(new Map())
const selectBatchRow = ref(new Map())
const leftFilterInfo = reactive({
  query: {
    queryParams: {
      //availableCalcQtyGt: 0
    },
    queryMap: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [{ type: 'button', label: '搜索', event: leftSearch }],
})
// 表格相关
const leftTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  height: '70%',
  data: [],
  fieldList: [],
})
const rightFilterInfo = reactive({
  query: {
    queryParams: {
      availableCalcQtyGt: 0,
    },
    queryMap: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [{ type: 'button', label: '搜索', event: rightSearch }],
})
// 表格相关
const rightTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  height: '70%',
  data: [],
  fieldList: [],
  query: {},
})
// 弹窗相关
const dialogInfo = reactive({
  title: '选择验收产品',
  btLoading: false,
  width: '90%',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: true,
      event: save,
      show: true,
    },
  ],
})

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})

watch(
  () => rightTableInfo.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        if (
          row.codeType === 1 ||
          row.codeType === 4 ||
          (row.codeType === 2 && !row.uniqueCode) ||
          (row.codeType === 3 && !row.factoryMainCode) ||
          (row.codeType === 3 && !row.factorySubCode)
        ) {
          let smallUnitQty = parseFloat(row.smallUnitQty || 0)
          let unitConvertCoefficient = row.unitConvertCoefficient || 1
          let largeUnitQty = parseFloat(row.largeUnitQty || 0)
          let editCalcQty = proxy.$fn.accAdd(
            proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
            smallUnitQty
          )
          let editQty = proxy.$fn.accDiv(editCalcQty, unitConvertCoefficient)
          row['editCalcQty'] = editCalcQty
          row['editQty'] = editQty
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(editCalcQty, row.price),
            unitConvertCoefficient
          )
          let newData = ''
          if (isSysGroup.value) {
            let key = setKey(clickRow.value)
            newData = selectBatchRow.value.get(key)
            if (newData && newData.length) {
              newData.forEach((item) => {
                if (item.id === row.id) {
                  item.largeUnitQty = row.largeUnitQty
                  item.smallUnitQty = row.smallUnitQty
                  item.editCalcQty = row.editCalcQty
                  item.editQty = row.editQty
                  item.sumAmount = row.sumAmount
                }
              })
              let key = setKey(clickRow.value)
              selectBatchRow.value.set(key, newData)
            }
          }
        }
      })
    }
  },
  {
    deep: true,
  }
)

let obj = {
  price: {
    label: '单价',
    value: 'price',
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    hidden: true,
    show: false,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
}
leftTableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
rightTableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  editQty: {
    label: '数量',
    value: 'editQty',
    type: 'slot',
    componentType: 'number',
    show: false,
    hidden: true,
    minWidth: '250px',
  },
})
rightFilterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
leftFilterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
getLeftCustomize()

function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.availableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.availableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row) {
  let largeUnitQty = parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.availableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
// 获取左侧产品列表
function getLeftList() {
  leftTableInfo.refresh = Math.random()
}
function leftSearch() {
  leftTableInfo.initCurpage = Math.random()
  leftTableInfo.refresh = Math.random()
}
function getRightList() {
  rightTableInfo.refresh = Math.random()
}
function rightSearch() {
  rightTableInfo.initCurpage = Math.random()
  rightTableInfo.refresh = Math.random()
  console.log(rightTableInfo)
}
function selectable() {
  if (isSysGroup.value) {
    return false
  } else {
    return true
  }
}
function save() {
  //条码类型 code_type：1无码，2系统唯一码，3原厂码，4批次码
  let _selectBatchRow = []
  if (isSysGroup.value) {
    let keyArr = [...clickRowMap.value.keys()]
    let valueArr = [...clickRowMap.value.values()]
    keyArr.forEach((item, index) => {
      let details = selectBatchRow.value.get(item)
      let data = setDetails(details)
      details = data.data
      valueArr[index].isChoice = true
      valueArr[index].details = details
      valueArr[index].sumAmount = data.sumAmount
      valueArr[index].largeUnitQty = data.largeUnitQty
      valueArr[index].smallUnitQty = data.smallUnitQty
      valueArr[index].calcQty = data.calcQty
      valueArr[index].qty = data.qty
    })
    _selectBatchRow = valueArr
  } else {
    _selectBatchRow = setDetails(selectRow.value).data
    if (_selectBatchRow.length) {
      let arr = proxy.$fn.deepClone(_selectBatchRow)
      _selectBatchRow.forEach((row, index) => {
        let item = arr[index]
        row.details = [item]
      })
    }
  }
  handleClose()
  emit('callback', _selectBatchRow)
}
function setDetails(data) {
  let sunAmount = 0
  let largeUnitQty = 0
  let smallUnitQty = 0
  let calcQty = 0
  if (data && data.length) {
    data.forEach((item) => {
      item.isChoice = true
      item.depotStockId = item.id
      if (
        item.codeType === 1 ||
        item.codeType === 4 ||
        (item.codeType === 2 && !item.uniqueCode) ||
        (item.codeType === 3 && !item.factoryMainCode) ||
        (item.codeType === 3 && !item.factorySubCode)
      ) {
        item.calcQty = item.editCalcQty || 0
        item.qty = item.editQty || 0
      }
      largeUnitQty = proxy.$fn.accAdd(largeUnitQty, item.largeUnitQty || 0)
      smallUnitQty = proxy.$fn.accAdd(smallUnitQty, item.smallUnitQty || 0)
      calcQty = proxy.$fn.accAdd(calcQty, item.calcQty || 0)
      item.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(item.calcQty, parseFloat(item.price)),
        item.unitConvertCoefficient
      )
      sunAmount += item.sumAmount
    })
    return {
      data: data,
      sumAmount: sunAmount,
      largeUnitQty: largeUnitQty,
      smallUnitQty: smallUnitQty,
      calcQty: calcQty,
      qty: proxy.$fn.accDiv(calcQty, data[0].unitConvertCoefficient || 1),
    }
  } else {
    return {
      data: [],
      sumAmount: sunAmount,
    }
  }
}
function leftHandleEvent(event, data) {
  switch (event) {
    case 'tableClickRow':
      if (data && data.id) {
        let newData = proxy.$fn.deepClone(data)
        newData.key = setKey(newData)
        clickRow.value = data
        for (let key in searchObj.value) {
          searchObj.value[key].value = newData[key]
        }
        rightFilterInfo.query.queryMap = {
          ...rightFilterInfo.query.queryMap,
          ...searchObj.value,
        }
        data.depotStockId = data.id
        rightTableInfo.api = props.api
        rightFilterInfo.query = {
          ...rightFilterInfo.query,
          ...props.query,
        }
        rightSearch()
        let key = setKey(clickRow.value)
        clickRowMap.value.set(key, data)
        if (!selectBatchRow.value.has(key)) {
          proxy.$refs['productTable'].toggleRowSelection(clickRow.value, true)
        }
      }
      break
  }
}
function setKey(item) {
  let key = ''
  groupArr.value &&
    groupArr.value.forEach((row, index) => {
      key =
        key + item[row.value] + (index === groupArr.value.length - 1 ? '' : '&')
    })
  return key
}
function rightHandleEvent(event, data) {
  let key = setKey(clickRow.value)
  switch (event) {
    case 'list':
      if (data.length) {
        let selectData
        if (isSysGroup.value) {
          selectData = selectBatchRow.value.get(key)
        } else {
          selectData = selectRow.value
        }
        data.forEach((row) => {
          if (
            row.codeType === 1 ||
            row.codeType === 4 ||
            (row.codeType === 2 && !row.uniqueCode) ||
            (row.codeType === 3 && !row.factoryMainCode) ||
            (row.codeType === 3 && !row.factorySubCode)
          ) {
            row.largeUnitQty = 0
            row.smallUnitQty = 0
            row.sumAmount = 0
          } else if (row.codeType === 2 || row.codeType === 3) {
            row.editCalcQty = row.calcQty
            row.editQty = row.qty
          }
          if (selectData && selectData.length) {
            selectData.forEach((item) => {
              if (item.id === row.id) {
                row.largeUnitQty = item.largeUnitQty
                row.smallUnitQty = item.smallUnitQty
                row.editCalcQty = item.editCalcQty
                row.editQty = item.editQty
                row.sumAmount = item.sumAmount
              }
            })
          }
        })
        rightTableInfo.data = data
        if (!selectBatchRow.value.has(key) && isSysGroup.value) {
          if ([...selectBatchRow.value.keys()].length) {
            if (!selectBatchRow.value.has(setKey(data[0]))) {
              proxy.$refs['batchNumberTable'].toggleRowSelection(data[0], true)
            }
          } else {
            proxy.$refs['batchNumberTable'].toggleRowSelection(data[0], true)
          }
        }
      }
      break
    case 'tableCheck':
      if (!isSysGroup.value) {
        selectRow.value = data
      } else {
        if (data.length) {
          let mapNew = _.groupBy(data, (item) => {
            let key = setKey(item)
            return key
          })
          let key = setKey(clickRow.value)
          if (!Object.keys(mapNew).includes(key)) {
            selectBatchRow.value.delete(key)
            clickRowMap.value.delete(key)
            proxy.$refs['productTable'].toggleRowSelection(
              clickRow.value,
              false
            )
            proxy.$refs['productTable'].setCurrentRow()
          } else {
            clickRowMap.value.set(key, clickRow.value)
            proxy.$refs['productTable'].toggleRowSelection(clickRow.value, true)
            for (let key in mapNew) {
              selectBatchRow.value.set(key, mapNew[key])
            }
          }
        } else {
          let key = setKey(clickRow.value)
          selectBatchRow.value.delete(key)
          clickRowMap.value.delete(key)
          proxy.$refs['productTable'].toggleRowSelection(clickRow.value, false)
        }
      }
      break
  }
  let len = isSysGroup.value
    ? [...selectBatchRow.value.keys()].length
    : selectRow.value.length
  if (len) {
    dialogInfo.btList[1].disabled = false
  } else {
    dialogInfo.btList[1].disabled = true
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
function getLeftCustomize() {
  let filterInfo = leftFilterInfo
  let param = { tableKey: props.leftTableKey }
  let obj = {}
  let groupList = []
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      leftTableInfo.fieldList = proxy.$fn.setFieldList(
        leftTableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = leftSearch
      })
      isSysGroup.value = false
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          obj[key] = {
            queryType: 'EQUALS',
            queryCategory: 'AND',
            ignoreEmptyValue: false,
            value: null,
          }
          groupList.push({ value: key })
          isSysGroup.value = true
        }
      }
      searchObj.value = obj
      groupArr.value = groupList
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...props.query,
      }
      filterInfo.query.queryParams = {
        ...filterInfo.query.queryParams,
        ...props.query.queryParams,
      }
      if (isSysGroup.value) {
        filterInfo.query.excludeQueryList = props.excludeQueryList
      } else {
        rightFilterInfo.query.excludeQueryList = props.excludeQueryList
      }
      leftTableInfo.api = props.api
      getRightCustomize()
      if (isSysGroup.value) {
        leftTableInfo.refresh = Math.random()
        setTimeout(() => {
          getLeftList()
        }, 0)
      }
    }
  })
}
function getRightCustomize() {
  let filterInfo = rightFilterInfo
  let param = { tableKey: props.rightTableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      rightTableInfo.fieldList = proxy.$fn.setFieldList(
        rightTableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = leftSearch
      })
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...props.query,
      }
      if (!isSysGroup.value) {
        rightTableInfo.api = props.api
        getRightList()
      }
    }
  })
}
</script>

<style scoped lang="scss">
.productTable :deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
.productTable
  :deep(.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner) {
  background-color: #6dc1a9;
  border-color: #6dc1a9;
}
.productTable
  :deep(.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after) {
  border-color: #ffffff;
}
</style>
